import React from "react";
import { Form, Input, Modal, Select } from "antd";
import { equals } from "@cbd/utils";
import { openNotificationWithIcon } from "../../../../utils/comm";

const { TextArea } = Input;
const { Option } = Select;

const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

@Form.create()
class CreateForm extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      appList: undefined,
      busiList: undefined,
    };
  }

  componentDidMount() {
    this.setFormValue();
  }

  componentDidUpdate(preProps) {
    const { data } = this.props;
    if (!equals(data, preProps.data)) {
      this.setFormValue();
    }
  }

  setFormValue = () => {
    const { data, form } = this.props;
    if (data) {
      const {
        formId,
        formKey = "",
        formName: name,
        description,
        tenantId,
        appId,
        busiId,
      } = data;
      this.formId = formId;
      form.setFieldsValue({
        key: `copy${formKey}`,
        name,
        description,
        tenantId,
        appId,
        busiId,
      });
      this.updateAppListAndBusiList(tenantId, appId);
    }
  };

  updateAppListAndBusiList = (tenantId, appId) => {
    const { tenantList } = this.props;
    let apps = [];
    let busi;

    if (tenantId) {
      [{ apps = [] }] = tenantList.filter(({ id }) => tenantId === id);
    } else {
      ({ appList: apps } = this.state);
    }

    if (appId) {
      [{ busi = [] }] = apps.filter(({ id }) => appId === id);
    }

    this.setState({
      appList: apps,
      busiList: busi,
    });
  }


  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch } = this.props;
    const actionType = this.formId ? "copy" : "add";
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const params = values;
      if (this.formId) params.originFormId = this.formId;
      dispatch({
        type: "FormConfigure/addOrCopyForm",
        payload: params,
        actionType,
      }).then((data) => {
        const { errCode, errMsg } = data;
        if (errCode === 0) {
          this.handleCancel();
          // form.resetFields();
          return;
        }
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || `${this.modelId ? "复制" : "添加"}失败`,
        );
      });
    });
  };

  handleCancel = () => {
    const { handleCreateVisible, form } = this.props;
    form.resetFields();
    handleCreateVisible(false);
  };

  render() {
    const { form, visible, confirmLoading, tenantList } = this.props;
    const { appList, busiList } = this.state;
    const { getFieldDecorator } = form;
    return (
      <Modal
        title="新建表单"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width="642px"
        centered
        confirmLoading={confirmLoading}
      >
        <Form>
          <Form.Item label="表单名称" {...formItemLayout1}>
            {getFieldDecorator("name", {
              initialValue: "",
              rules: [
                { required: true, message: "请输入表单名称" },
                { max: 20, message: "表单名称长度不能超过20" },
              ],
            })(<Input maxLength={20} placeholder="请输入表单名称" />)}
          </Form.Item>
          <Form.Item label="表单编码" {...formItemLayout1}>
            {getFieldDecorator("key", {
              initialValue: "",
              rules: [
                { required: true, message: "请输入表单编码" },
                { max: 20, message: "编码长度不能超过20" },
                {
                  pattern: /^[a-zA-Z_][a-zA-Z_0-9-]*$/,
                  message:
                    "支持字母、数字、下划线、中划线，须以字母或者下划线开头",
                },
              ],
            })(<Input maxLength={20} placeholder="请输入表单编码" />)}
          </Form.Item>
          <Form.Item label="表单说明" {...formItemLayout1}>
            {getFieldDecorator("description", {
              initialValue: "",
              rules: [{ max: 100, message: "说明长度不能超过100" }],
            })(<TextArea placeholder="请输入表单说明" rows={4} />)}
          </Form.Item>
          <Form.Item label="租户" {...formItemLayout1}>
            {getFieldDecorator("tenantId", {
              // initialValue: "",
              rules: [{ required: true, message: "请选择所属租户" }],
            })(
              <Select
                placeholder="请选择所属租户"
                onChange={(id) => {
                  /*
                  const [{ apps = [] }] = tenantList.filter(({ id: _id }) => _id === id);
                  this.setState({
                    appList: apps,
                    busiList: undefined,
                  });
                  */
                  this.updateAppListAndBusiList(id);
                  form.setFieldsValue({
                    appId: undefined,
                    busiId: undefined,
                  });
                }}
              >
                {tenantList.map((selectItem) => (
                  <Option value={selectItem.id} key={selectItem.id}>
                    {selectItem.tenantName}
                  </Option>
                ))}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="应用" {...formItemLayout1}>
            {getFieldDecorator("appId", {
              // initialValue: "",
              rules: [{ required: true, message: "请选择所属应用" }],
            })(
              <Select
                placeholder="请选择所属应用"
                disabled={!appList}
                onChange={(id) => {
                  /*
                  const [{ busi = [] }] = appList.filter(({ id: _id }) => _id === id);
                  this.setState({
                    busiList: busi,
                  });
                  */
                  this.updateAppListAndBusiList(null, id);
                  form.setFieldsValue({
                    busiId: undefined,
                  });
                }}
              >
                {(appList || []).map((selectItem) => (
                  <Option value={selectItem.id} key={selectItem.id}>
                    {selectItem.appName}
                  </Option>
                ))}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="业务" {...formItemLayout1}>
            {getFieldDecorator("busiId", {
              // initialValue: "",
              rules: [{ required: true, message: "请选择所属业务" }],
            })(
              <Select placeholder="请选择所属业务" disabled={!busiList}>
                {(busiList || []).map((selectItem) => (
                  <Option value={selectItem.id} key={selectItem.id}>
                    {selectItem.busiName}
                  </Option>
                ))}
              </Select>,
            )}
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}
export default CreateForm;
